package com.kylin.common.security.service;

import com.google.code.kaptcha.Producer;
import com.kylin.common.core.beans.ResultBean;
import com.kylin.common.redis.service.RedisService;
import com.kylin.common.security.exception.AuthErrorMessage;
import com.kylin.common.security.exception.CaptchaException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 验证码实现处理
 *
 * @author wuhao
 */
@Service
public class CaptchaService
{
    @Autowired
    private Producer producer;

    @Autowired
    private RedisService redisService;

    /**
     * 验证码 redis key
     */
    private static final String CAPTCHA_CODE_KEY = "captcha_codes:";
    /**
     * 验证码有效期（分钟）
     */
    public static final Integer CAPTCHA_EXPIRATION = 2;

    /**
     * 生成验证码
     */
    public ResultBean<Object> createCaptcha()
    {
        try {
            // 生成验证码
            String capText = producer.createText();
            String capStr = capText.substring(0, capText.lastIndexOf("@"));
            String verifyCode = capText.substring(capText.lastIndexOf("@") + 1);
            BufferedImage image = producer.createImage(capStr);
            // 保存验证码信息
            String uuid = UUID.randomUUID().toString();
            String verifyKey = CAPTCHA_CODE_KEY + uuid;

            redisService.setCacheObject(verifyKey, verifyCode, CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
            // 转换流信息写出
            FastByteArrayOutputStream os = new FastByteArrayOutputStream();
            try
            {
                ImageIO.write(image, "jpg", os);
            }
            catch (IOException e)
            {
                throw  new CaptchaException(AuthErrorMessage.CAPTCHA_CREATE_FAILED.getMessage());
            }

            BASE64Encoder encoder = new BASE64Encoder();
            return ResultBean.onSuccess()
                    .put("uuid", uuid)
                    .put("img", encoder.encode(os.toByteArray()));

        }catch (Exception e) {
            throw  new CaptchaException(AuthErrorMessage.CAPTCHA_CREATE_FAILED.getMessage());
        }
    }

    /**
     * 校验验证码
     */
    public void checkCaptcha(String code, String uuid)
    {
        if(!"kylin".equals(code)) {
            if (StringUtils.isEmpty(code)) {
                throw new CaptchaException(AuthErrorMessage.CAPTCHA_NOTNULL.getMessage());
            }
            if (StringUtils.isEmpty(uuid)) {
                throw new CaptchaException(AuthErrorMessage.CAPTCHA_CHECK_ERROR.getMessage());
            }
            String verifyKey = CAPTCHA_CODE_KEY + uuid;
            String captcha = redisService.getCacheObject(verifyKey);
            redisService.deleteObject(verifyKey);

            // add by wuhao 新增便捷验证码 kylin at 20210418
            if (!code.equalsIgnoreCase(captcha)) {
                throw new CaptchaException(AuthErrorMessage.CAPTCHA_CHECK_ERROR.getMessage());
            }
        }
    }
}
